package com.zhugang.week14.concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @program algorithms
 * @description: BlockingQueueTest
 * @author: chanzhugang
 * @create: 2022/09/15 22:31
 */
public class BlockingQueueTest {

    public static void main(String[] argv) {
        BlockingQueue<Integer> queue;
        queue = new ArrayBlockingQueue<Integer>(10);
        //queue = new LinkedBlockingQueue<Integer>();
        //queue = new LinkedBlockingDeque<>();
        //queue = new PriorityBlockingQueue<>();
        //queue = new LinkedTransferQueue<Integer>();
        //queue = new SynchronousQueue<>();
        //queue = new DelayQueue<>();

        // Producer
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    // 阻塞，响应线程中断
                    queue.put((int) (Math.random() * 1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }

        // Consumer
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                while (true) {
                    Integer x = null;
                    try {
                        // 阻塞，响应线程中断
                        x = queue.take();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Receive:" + x);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}